package com.android.manghe.orderpay.presenter;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import com.alipay.sdk.app.PayTask;
import com.android.base.frame.presenter.XPresenter;
import com.android.base.okhttp.okUtil.OKHttpUtil;
import com.android.base.okhttp.okUtil.base.NetBean;
import com.android.base.okhttp.okUtil.callback.GsonBaseBack;
import com.android.base.tools.ToastUtil;
import com.android.manghe.cache.StatusHolder;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.model.*;
import com.android.manghe.config.ConstantsUrl;
import com.android.manghe.mine.model.AddressInfo;
import com.android.manghe.orderpay.activity.AuctionOrderPayActivity;
import com.android.manghe.orderpay.model.AuctionOrderInfoRes;
import com.android.manghe.utils.ApiCrypter;
import com.android.manghe.utils.PayResult;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import okhttp3.Call;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class PAuctionOrder extends XPresenter<AuctionOrderPayActivity> {

    private String orderId = "";
    public AddressInfo currentAddress;
    public PaymentTypeRes.DataBean.PaymentBean selectedPayBean;
    public AuctionOrderInfoRes.DataBean orderInfo;

    public void setCurrentAddress(AddressInfo currentAddress) {
        this.currentAddress = currentAddress;
    }

    public void setPayType(PaymentTypeRes.DataBean.PaymentBean selectedPayBean) {
        this.selectedPayBean = selectedPayBean;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public void loadOrderInfo() {
        HashMap<String, String> data = new HashMap<>();
        data.put("order_id", orderId);
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
headMap.put("PLATFORM", "android");
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.AUCTIONORDERDETAIL, data, headMap)
                .get()
                .execute(new GsonBaseBack<AuctionOrderInfoRes>() {

                    @Override
                    public void onSuccess(Call call, AuctionOrderInfoRes res) {
                        if (res != null && res.code == 0 && res.data != null) {
                            orderInfo = res.data;
                            getV().showGoodDetail(res.data);
                        } else {
                            getV().showGoodDetail(null);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        getV().showGoodDetail(null);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void loadAddressList() {
        HashMap<String, String> data = new HashMap<>();
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
headMap.put("PLATFORM", "android");
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.MEMBERADDRESSLIST, data, headMap)
                .get()
                .execute(new GsonBaseBack<AddressInfo>() {

                    @Override
                    public void onSuccess(Call call, AddressInfo addressInfo) {
                        if (addressInfo != null && addressInfo.code == 0 && addressInfo.data != null && !addressInfo.data.isEmpty()) {
                            for (AddressInfo addr : addressInfo.data) {
                                if (TextUtils.equals(addr.is_default, "1")) {
                                    getV().showAddress(addr);
                                    return;
                                }
                            }
                            getV().showAddress(addressInfo.data.get(0));
                        } else {
                            getV().showAddress(null);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        getV().showAddress(null);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getPaymentType() {
        HashMap<String, String> data = new HashMap<>();
        new OKHttpUtil(getV()).url(ConstantsUrl.domain + ConstantsUrl.FLOWPAYMENT, data)
                .get()
                .execute(new BaseBack<PaymentTypeRes>() {

                    @Override
                    public void onSuccess(Call call, PaymentTypeRes res) {
                        if (res != null && res.data != null && res.data.payment != null && res.data.payment.size() != 0) {
                            getV().updatePayments(res.data.payment);
                            selectedPayBean = res.data.payment.get(0);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                    }

                    @Override
                    public void onComplete() {
                        getV().hideLoadingDialog();
                    }
                });

    }

    public void toPay(String mark) {
        if (orderInfo == null || selectedPayBean == null) {
            return;
        }
        StatusHolder.mCurrentPayType = 1;
        getV().showLoadingDialog();
        HashMap<String, String> data = new HashMap<>();
        data.put("pay_id", selectedPayBean.pay_id);
        data.put("order_id", orderInfo.id);
        data.put("address_id", currentAddress.id);
        data.put("pre", "0");
        data.put("remark", mark);
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
headMap.put("PLATFORM", "android");
        if (selectedPayBean.pay_code.equals("alipayapp")) {
            new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.AUCTIONCHECKOUT, headMap)
                    .post(data).build()
                    .execute(new BaseBack<AliPayRes>() {

                        @Override
                        public void onSuccess(Call call, AliPayRes res) {
                            getV().hideLoadingDialog();
                            if (res != null && res.data != null && res.data.paycode != null) {
                                toPayByAli(res.data.paycode);
                            } else {
                                getV().payFail();
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            super.onFailure(e);
                            getV().hideLoadingDialog();
                            getV().payFail();
                        }

                        @Override
                        public void onComplete() {
                            getV().hideLoadingDialog();
                        }
                    });
        } else if (selectedPayBean.pay_code.equals("wxpayapp") || selectedPayBean.pay_code.equals("wxpayapp2")) {
            new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.AUCTIONCHECKOUT, headMap)
                    .post(data).build()
                    .execute(new BaseBack<WXPayRes>() {

                        @Override
                        public void onSuccess(Call call, WXPayRes res) {
                            getV().hideLoadingDialog();
                            if (res != null && res.data != null && res.data.paycode != null && res.data.paycode.appid != null) {
                                new OKHttpUtil(getV()).url(ConstantsUrl.domain + (selectedPayBean.pay_code.equals("wxpayapp") ? ConstantsUrl.WX_CONFIG : ConstantsUrl.WX_CONFIG2))
                                        .get()
                                        .execute(new GsonBaseBack() {
                                            @Override
                                            public void onSuccess(Call call, String json) {
                                                getV().hideLoadingDialog();
                                                NetBean<String> netBean = new Gson().fromJson(json, NetBean.class);
                                                if (netBean != null && netBean.code == 0 && !TextUtils.isEmpty(netBean.data)) {
                                                    try {
                                                        String dataString = URLDecoder.decode(new String(new ApiCrypter().decrypt(netBean.data), "UTF-8"), "UTF-8");
                                                        if (!TextUtils.isEmpty(dataString)) {
                                                            WechatConfig config = new Gson().fromJson(dataString, WechatConfig.class);
                                                            if (config != null) {
                                                                if (!TextUtils.isEmpty(config.wxpay_app_id)) {
                                                                    ConstantsUrl.PAY_WX_APPID = config.wxpay_app_id;
                                                                }
                                                                toPayByWx(res.data.paycode);
                                                            } else {
                                                                getV().payFail();
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                        getV().payFail();
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onFailure(Exception e) {
                                                super.onFailure(e);
                                                getV().hideLoadingDialog();
                                                getV().payFail();
                                            }

                                            @Override
                                            public void onComplete() {

                                            }
                                        });
                            } else {
                                getV().payFail();
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            super.onFailure(e);
                            getV().hideLoadingDialog();
                            getV().payFail();
                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        }else {
            new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.AUCTIONCHECKOUT, headMap)
                    .post(data).build()
                    .execute(new BaseBack<AliPayRes>() {

                        @Override
                        public void onSuccess(Call call, AliPayRes res) {
                            getV().hideLoadingDialog();
                            if (res != null && res.data != null && res.data.paycode != null) {
                                if(selectedPayBean.pay_code.equals("yipayweixinh5")){
                                    //微信H5，打开手机浏览器
                                    getV().toPayByBrowser(res.data.paycode, res.data.log_id);
                                } else {
                                    //其他就打开浏览器支付。例如盛付通
                                    getV().toPayByH5(res.data.paycode);
                                }
                            } else {
                                getV().payFail();
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            super.onFailure(e);
                            getV().hideLoadingDialog();
                            getV().payFail();
                        }

                        @Override
                        public void onComplete() {
                            getV().hideLoadingDialog();
                        }
                    });
        }
    }


    private static final int SDK_PAY_FLAG = 1;
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
//                        ToastUtil.showShort(getV(), "支付成功");
                        getV().paySuccess();
                    } else {
                        if (TextUtils.equals(resultStatus, "8000") || TextUtils.equals(resultStatus, "6004")) {
                            ToastUtil.showShort(getV(), "支付结果确认中");
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            ToastUtil.showShort(getV(), "支付取消");
                        } else if (TextUtils.equals(resultStatus, "6002")) {
                            ToastUtil.showShort(getV(), "网络异常");
                        } else if (TextUtils.equals(resultStatus, "5000")) {
                            ToastUtil.showShort(getV(), "重复请求");
                        } else {
                            // 其他值就可以判断为支付失败
                            ToastUtil.showShort(getV(), "支付失败");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    private void toPayByAli(String orderInfo) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(getV());
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void toPayByWx(WXPayRes.DataBean.PaycodeBean bean) {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(getV(), ConstantsUrl.PAY_WX_APPID, true);
        iwxapi.registerApp(ConstantsUrl.PAY_WX_APPID);
        PayReq req = new PayReq();
        req.appId = ConstantsUrl.PAY_WX_APPID;
        req.partnerId = bean.partnerid;
        req.prepayId = bean.prepayid;
        req.packageValue = bean.wxpackage;
        req.nonceStr = bean.noncestr;
        req.timeStamp = bean.timestamp + "";
        req.sign = bean.sign;
        iwxapi.sendReq(req);
    }

    public void checkOrderStatus(String orderId){
        getV().showLoadingDialog();
        new OKHttpUtil(getV()).url(ConstantsUrl.domain + String.format(ConstantsUrl.IsOrderPayed, orderId))
                .get()
                .execute(new GsonBaseBack() {
                    @Override
                    public void onSuccess(Call call, String json) {
                        getV().hideLoadingDialog();
                        SimpleResult res = new Gson().fromJson(json, SimpleResult.class);
                        if(res != null) {
                            if (res.is_success == 1) {
                                getV().paySuccess();
                            } else {
                                getV().payFail();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        getV().hideLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        getV().hideLoadingDialog();
                    }
                });
    }
}
